package com.tx.utils.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author: tcx
 * @description: 登录拦截器
 * @Date: 2019/11/10
 **/
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //用户登陆、注册操作放行
        String url = httpServletRequest.getRequestURI();
        if (url.toLowerCase().indexOf("user")>0){
            return true;
        }
        //对首页放行
        if (url.toLowerCase().indexOf("index")>0){
            return true;
        }
        //对已登录用户放行
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("user")!=null){
            return true;
        }
        httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/user/to_login.do");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
